#!/usr/bin/env python
# coding=utf8
import matplotlib

matplotlib.use('Agg')
import torch
from flask import Flask
from flask import request
from flask import make_response, Response
from sys import argv
import os
import numpy as np
import autocode_torch
from torch.autograd import Variable

app = Flask(__name__)
_rnn, _rnn_time = None, None

torchfilename = 'data/FXUSDJPY_autoencoder_1.pkl'


def get_EMA(df, a=0.7):
    ema = df
    for i in range(len(df)):
        if i == 0:
            ema[i] = df[i]
        if i > 0:
            ema[i] = (1 - a) * ema[i - 1] + a * df[i]
    return ema


def LoadModule(torchfilename=torchfilename):
    global _rnn, _rnn_time
    rmt = os.path.getmtime(torchfilename)
    if _rnn_time != rmt:
        _rnn = None
    if not _rnn:
        _rnn = torch.load(torchfilename)
        _rnn_time = rmt
        print("\nRNN reload <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
    return _rnn


def getrnn2(indicData):
    trandata = []
    for i in range(len(indicData) - autocode_torch.span):
        line = []
        for j in indicData[i:i + autocode_torch.span]:
            line.append(j)
        trandata.append(line)
    trandata = np.array(trandata, dtype=np.float32)
    trandata = autocode_torch.processInput(trandata)
    disres = trandata[:, -1]
    get_EMA(disres, 0.3)
    return disres


def getrnn(datalist):
    trandata = []
    for i in range(len(datalist) - autocode_torch.span):
        line = []
        for j in datalist[i:i + autocode_torch.span]:
            line.append(j)
        trandata.append(line)
    trandata = np.array(trandata, dtype=np.float32)
    trandata = autocode_torch.processInput(trandata)
    trant = Variable(torch.from_numpy(trandata))

    autoencoder = torch.load(torchfilename)
    encoded, decoded = autoencoder(trant)
    disres = decoded.data.cpu().numpy()
    disres = disres[:, -1]
    get_EMA(disres, 0.9)
    return disres


@app.route('/')
def hello_world():
    return 'hello world'


def Response_headers(content):
    resp = Response(content)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp


@app.route('/', methods=['POST'])
@app.route('/test', methods=['POST', 'GET'])
@app.route('/tree', methods=['POST', 'GET'])
@app.route('/svm', methods=['POST', 'GET'])
@app.route('/lstm', methods=['POST', 'GET'])
def test():
    if request.method == 'GET':
        return 'asdfasdf'
    if request.method == 'POST':
        datax = request.form.to_dict()
        i = datax
        slide = int(1 - float(i['slide']) * 2)
        ordernumber = i['ordernumber']
        count = i['count'] if 'count' in i.keys() else 'no count number'
        symbol = i['symbol'][:6] if 'symbol' in i.keys() else 'no symbol'
        # symbol = symbol.split(".")[0]
        indicData = i['indicData']
        indicData = indicData.strip().split(",")
        indicData = [float(i) for i in indicData[:-1]]
        indicData.reverse()
        indicData = indicData[-1500:]
        global torchfilename
        torchfilename = 'data/FX{}_{}_autoencoder.pkl'.format(symbol, 5)
        ar = getrnn(indicData)
        short = [abs(ar[i] - ar[i - 1]) for i in range(1, len(ar))]

        print('\n', '方向:', slide, ' 订单数:', ordernumber, ' 账号：', count, ' 产品：', symbol, '\n', ar[-5:], 'pred', argv[1])
        res = [0, 0, 0, 0]
        dif = 0.8
        df2 = 0.5
        print('最近信号：', max(short[-5:]), '所有信号：', max(short))
        if max(short[-5:]) > 0.9:
            print('异常信号！', max(short[-5:]))
            return '0000'

        if ar[-2] < -dif < ar[-1] < -df2:
            res[0] = 1
        if ar[-2] > dif > ar[-1] > df2:
            res[1] = 1
        if (ar[-1] > -df2) and slide in [1, -3]:
            res[2] = 1
        if (ar[-1] < df2) and slide in [-1, -5]:
            res[3] = 1

        # return '22'
        return str(res[0]) + str(res[1]) + str(res[2]) + str(res[3])


if __name__ == '__main__':
    # autoencoder = torch.load(autocode_torch.torchfilename)
    # autoencoder.eval()

    app.run('0.0.0.0', port=int(argv[1]) if len(argv) == 2 else 8080, debug=False, threaded=True)
